package com.xpoint.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xpoint.backend.common.BaseContext;
import com.xpoint.backend.common.R;
import com.xpoint.backend.entity.EmailCode;
import com.xpoint.backend.entity.User;
import com.xpoint.backend.service.EmailCodeService;
import com.xpoint.backend.service.UserService;
import com.xpoint.backend.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/common")
@Slf4j
//公共类
public class CommonController {
    @Value("${dish.imgpath}")
    private String dishImgPath;
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private UserService userService;

    @Autowired
    private EmailCodeService emailCodeService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/upload")
//    接收前端传输过来的文件.
    public R<String> uploadImg(MultipartFile file) {
        try {
//            构造一个文件类,填入默认的路径
            File file1 = new File(dishImgPath);
//            如果文件路径不存在,就创建文件夹
            if (!file1.exists()) {
                file1.mkdir();
            }
//            get接收过来的文件名称,截取.以后的字符串
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//            UUID随机生成字符串,拼接成新的文件名
            String fileName = UUID.randomUUID().toString() + suffix;
//            将文件转移到指定的路径,因为接收的这个文件是临时的,程序停止以后会删掉临时资源
            file.transferTo(new File(dishImgPath + fileName));
            System.out.println("来过" + fileName);
            return R.success(fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("失败");
        }
    }

    @GetMapping("/download")
//    将文件响应给前端
    public void downloadImg(String name, HttpServletResponse response) {
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(dishImgPath + name));
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
//            响应给浏览的文件类型
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
//            读取文件内容,并响应给前端!
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            System.err.println("图片出错啦！！！！！！！！！！");
            e.printStackTrace();
        }
    }


    //    获取邮箱验证码
    @GetMapping("/getEmailCode/{email}")
    public R<String> getEmailCode(@PathVariable String email, HttpServletRequest request) {
//        随机的验证码
        String code = ValidateCodeUtils.generateValidateCode4String(6);
//        创建一个条件构造器,根据邮件查询用户信息
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getEmail, email);
        User one = userService.getOne(lambdaQueryWrapper);

        /*   通过数据库保存验证码的方法
        将验证码和邮箱号保存到数据库中
        EmailCode emailCode = new EmailCode();
        emailCode.setEmail(email);
        emailCode.setCode(code);
        先删除当前邮箱的所有数据
        LambdaQueryWrapper<EmailCode> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(EmailCode::getEmail,email);
        emailCodeService.remove(lambdaQueryWrapper1);

        再保存当前邮箱和验证码
        emailCodeService.save(emailCode);*/

//        设置到redis中，有效期是5分钟
        redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);
        String context = "<head>\n" +
                "    <base target=\"_blank\" />\n" +
                "    <style type=\"text/css\">::-webkit-scrollbar{ display: none; }</style>\n" +
                "    <style id=\"cloudAttachStyle\" type=\"text/css\">#divNeteaseBigAttach, #divNeteaseBigAttach_bak{display:none;}</style>\n" +
                "    <style id=\"blockquoteStyle\" type=\"text/css\">blockquote{display:none;}</style>\n" +
                "    <style type=\"text/css\">\n" +
                "        body{font-size:14px;font-family:arial,verdana,sans-serif;line-height:1.666;padding:0;margin:0;overflow:auto;white-space:normal;word-wrap:break-word;min-height:100px}\n" +
                "        td, input, button, select, body{font-family:Helvetica, 'Microsoft Yahei', verdana}\n" +
                "        pre {white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word;width:95%}\n" +
                "        th,td{font-family:arial,verdana,sans-serif;line-height:1.666}\n" +
                "        img{ border:0}\n" +
                "        header,footer,section,aside,article,nav,hgroup,figure,figcaption{display:block}\n" +
                "        blockquote{margin-right:0px}\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body tabindex=\"0\" role=\"listitem\">\n" +
                "<table width=\"700\" border=\"0\" align=\"center\" cellspacing=\"0\" style=\"width:700px;\">\n" +
                "    <tbody>\n" +
                "    <tr>\n" +
                "        <td>\n" +
                "            <div style=\"width:700px;margin:0 auto;border-bottom:1px solid #ccc;margin-bottom:30px;\">\n" +
                "                <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"700\" height=\"39\" style=\"font:12px Tahoma, Arial, 宋体;\">\n" +
                "                    <tbody><tr><td width=\"210\"></td></tr></tbody>\n" +
                "                </table>\n" +
                "            </div>\n" +
                "            <div style=\"width:680px;padding:0 10px;margin:0 auto;\">\n" +
                "                <div style=\"line-height:1.5;font-size:14px;margin-bottom:25px;color:#4d4d4d;\">\n" +
                "                    <strong style=\"display:block;margin-bottom:15px;\">尊敬的用户：<span style=\"color: #12a4b7;font-size: 18px\">" + one.getName() + "</span><span style=\"color:#f60;font-size: 16px;\"></span> , 您好！</strong>\n" +
                "                    <strong style=\"display:block;margin-bottom:15px;\">\n" +
                "                        您正在进行<span style=\"color: red\">找回密码</span>操作，请在验证码输入框中输入：<span style=\"color:#f60;font-size: 24px\">" + code + "</span>，以完成操作。\n" +
                "                    </strong>\n" +
                "                </div>\n" +
                "                <div style=\"margin-bottom:30px;\">\n" +
                "                    <small style=\"display:block;margin-bottom:20px;font-size:12px;\">\n" +
                "                        <p style=\"color:#747474;\">\n" +
                "                            注意：此操作可能会修改您的密码、登录邮箱或绑定手机。如非本人操作，请及时登录并修改密码以保证帐户安全\n" +
                "                            <br>（工作人员不会向你索取此验证码，请勿泄漏！)\n" +
                "                        </p>\n" +
                "                    </small>\n" +
                "                </div>\n" +
                "            </div>\n" +
                "            <div style=\"width:700px;margin:0 auto;\">\n" +
                "                <div style=\"padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;\">\n" +
                "                    <p>此为系统邮件，请勿回复<br>\n" +
                "                        请保管好您的邮箱，避免账号被他人盗用\n" +
                "                    </p>\n" +
                "                    \n" +
                "                </div>\n" +
                "            </div>\n" +
                "        </td>\n" +
                "    </tr>\n" +
                "    </tbody>\n" +
                "</table>\n" +
                "</body>";
        try {
            helper.setFrom("1150250963@qq.com");//邮箱发送者
            helper.setTo(email);//邮箱接收者
            helper.setSubject("找回密码");//邮箱的主题
            helper.setSentDate(new Date());//发送时间:当前时间
            //第一个参数要发送的内容，第二个参数是不是Html格式。
            helper.setText(context, true);
            mailSender.send(mimeMessage);
            return R.success("获取成功,请前往邮箱查询" + email);
        } catch (MessagingException e) {
            e.printStackTrace();
            return R.error("获取失败,异常信息:" + e);
        }
    }

    @PutMapping("/updatePassword")
    public R<String> updatePassword(@RequestBody EmailCode emailCode) {
        if (emailCode != null) {
//          邮箱
            String email = emailCode.getEmail();
//          验证码
            String code = emailCode.getCode();
//            获取redis储存的值
            String o = (String) redisTemplate.opsForValue().get(email);

            if (o.equals(code)) {
//                  如果验证码一致就可以修改密码
                LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
//                MD5加密密码
                String newpassword = DigestUtils.md5DigestAsHex(emailCode.getPassword().getBytes());
//                update * from user set password=emailCode.getPassword() where email =emailCode.getEmail()
                lambdaUpdateWrapper
                        .eq(User::getEmail, emailCode.getEmail())
                        .set(User::getPassword, newpassword);
                if (userService.update(lambdaUpdateWrapper)) {
                    return R.success("恭喜您,修改密码成功!");
                }
                return R.error("未知错误");
            }


//            创建查询构造器
            LambdaQueryWrapper<EmailCode> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(EmailCode::getEmail, emailCode.getEmail());
            EmailCode one = emailCodeService.getOne(lambdaQueryWrapper);

            if (one.getCode().equals(emailCode.getCode())) {
//                创建更新条件构造器

            }
        }
        return R.error("修改密码失败,请检查验证码是否正确");
    }

}
